package com.wxg.spring.boot.blog.v2.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.wxg.spring.boot.blog.v2.domain.UserV2;
import com.wxg.spring.boot.blog.v2.repository.UserRepositoryV2;

/**
 * {@link UserV2}
 * <p>
 * CreateTime: 2018年10月30日 下午2:46:53
 *
 * @author wxg
 */
@RestController
@RequestMapping("/usersV2")
public class UserControllerV2 {

    @Autowired
    private UserRepositoryV2 userRepository;

    @GetMapping
    public ModelAndView list(Model model) {
        model.addAttribute("userList", userRepository.findAll());
        model.addAttribute("title", "用户管理");
        return new ModelAndView("v2/users/list", "userModel", model);
    }

    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Long id, Model model) {
        UserV2 user = userRepository.findById(id).get();
        model.addAttribute("user", user);
        model.addAttribute("title", "查看用户");
        return new ModelAndView("v2/users/view", "userModel", model);
    }

    /**
     * 获取表单页面
     * CreateTime: 2018年10月29日 上午11:06:55
     *
     * @param model
     * @return
     * @author wxg
     */
    @GetMapping("/form")
    public ModelAndView createForm(Model model) {
        model.addAttribute("user", new UserV2(null, null, null));
        model.addAttribute("title", "创建用户");
        return new ModelAndView("v2/users/form", "userModel", model);
    }

    @PostMapping
    public ModelAndView create(UserV2 user) {
        user = userRepository.save(user);
        return new ModelAndView("redirect:/usersV2");
    }

    @GetMapping(value = "delete/{id}")
    public ModelAndView delete(@PathVariable("id") Long id, Model model) {
        userRepository.deleteById(id);

        model.addAttribute("userList", userRepository.findAll());
        model.addAttribute("title", "删除用户");
        return new ModelAndView("v2/users/list", "userModel", model);
    }

    @GetMapping(value = "modify/{id}")
    public ModelAndView modifyForm(@PathVariable("id") Long id, Model model) {
        UserV2 user = userRepository.findById(id).get();

        model.addAttribute("user", user);
        model.addAttribute("title", "修改用户");
        return new ModelAndView("v2/users/form", "userModel", model);
    }
}
